from fastapi import FastAPI, UploadFile, Form
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from typing import Optional
from pathlib import Path
import time, shutil
from rag_core import build_kg_from_file, ask_question_with_kg

# pip install python-multipart

app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")

UPLOAD_FOLDER = Path("uploads")
UPLOAD_FOLDER.mkdir(exist_ok=True)

chat_history = []

@app.post("/api/ask")
async def handle_qa(question: str = Form(...), file: Optional[UploadFile] = None):
    if file:
        filepath = UPLOAD_FOLDER / file.filename
        with open(filepath, "wb") as f:
            shutil.copyfileobj(file.file, f)
        triples = build_kg_from_file(filepath)
        answer = ask_question_with_kg(question, triples)
    else:
        triples = []
        answer = ask_question_with_kg(question)

    chat_history.append({ "q": question, "a": answer })
    return JSONResponse({ "answer": answer, "triples": triples, "history": chat_history })

@app.get("/api/uploads")
def list_uploaded():
    return [
        { "filename": f.name, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(f.stat().st_mtime)) }
        for f in sorted(UPLOAD_FOLDER.glob("*"), key=lambda x: -x.stat().st_mtime)
    ]

@app.get("/")
def index():
    return JSONResponse({ "message": "Use /static/index.html" })

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, port=8000)
